package org.common.utils.rpc.entity;
import org.common.utils.id.IdTool;

import java.util.Arrays;
import java.util.concurrent.CompletableFuture;

/**
 * Rpc请求实体
 * @author zhouzhibing
 * @date 2025/11/15 19:16
 */
public class RpcRequest {
    /**
     * 请求id
     */
    private final long requestId;
    /**
     * 元数据
     */
    private final Metadata metadata;
    /**
     * 请求参数
     */
    private final Object[] args;
    /**
     * 创建时间戳
     */
    private transient final long createTime;
    /**
     * 异常响应结果
     */
    private transient CompletableFuture<Object> future;
    /**
     * toString字符串
     */
    private transient String toString;

    /**
     * 创建Rpc请求
     * @param metadata 元数据
     * @param args 请求参数
     */
    public RpcRequest(Metadata metadata , Object[] args) {
        this.requestId = IdTool.newId();
        this.metadata = metadata;
        this.args = args;
        this.createTime = System.currentTimeMillis();
    }

    public long getRequestId() {
        return requestId;
    }

    public Metadata getMetadata() {
        return metadata;
    }

    public Object[] getArgs() {
        return args;
    }

    public long getCreateTime() {
        return createTime;
    }

    /**
     * 获取第一个参数
     * @return 参数对象
     */
    public Object getFirstArg() {
        if(args == null || args.length == 0) {
            return null;
        }
        return args[0];
    }

    /**
     * 设置响应结果
     * @param future 响应结果
     */
    public <T> void setFuture(CompletableFuture<T> future) {
        this.future = (CompletableFuture<Object>)future;
    }

    /**
     * 获取响应结果
     * @return 响应结果
     */
    public <T> CompletableFuture<T> getFuture() {
        return (CompletableFuture<T>)future;
    }

    @Override
    public String toString() {
        if(toString != null) {
            return toString;
        }

        return toString = "RpcRequest{" +
                "requestId=" + requestId +
                ", metadata=" + metadata +
                ", args=" + Arrays.toString(args) +
                '}';
    }
}
